package com.chenyongjing.design.pattern.observer.mouseevent.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 抽象的被观察者
 * @Author chen
 * @Date 2022/12/5 22:13
 */
public abstract class EventContext {
    protected Map<String,Event> evets = new HashMap<>();

    public void addListener(String eventType, EventListener target, Method callback){
        evets.put(eventType,new Event(target,callback));
    }

    public void addListener(String eventType, EventListener target) {
        try {
            this.addListener(eventType, target, target.getClass().getMethod("on" + toUpperFirstCase(eventType), Event.class));
        }catch (NoSuchMethodException e){
            return;
        }
    }

    protected  String toUpperFirstCase(String eventType){
        char[] chars = eventType.toCharArray();
        chars[0] -= 32;
        return  String.valueOf(chars);

    }

    private void trigger(Event event){
        event.setSource(this);
        event.setTime(System.currentTimeMillis());
        if(event.getCallback() != null){
            try {
                event.getCallback().invoke(event.getTarget(),event);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    }

    protected void trigger(String eventType) {
        if (!this.evets.containsKey(eventType)){
            return;
        }
        trigger(this.evets.get(eventType).setTrigger(eventType));
    }
}
